import 'package:flutter/rendering.dart';
import 'package:flutter/scheduler.dart';
import 'package:flutter/widgets.dart';

typedef AfterLayoutCallback = Function(RenderAfterLayout ral);

class XHAfterLayout extends SingleChildRenderObjectWidget {
  const XHAfterLayout({
    super.key,
    required this.callback,
    super.child,
  });

  @override
  RenderObject createRenderObject(BuildContext context) {
    return RenderAfterLayout(callback);
  }

  @override
  void updateRenderObject(context, RenderAfterLayout renderObject) {
    renderObject.callback = callback;
  }

  final AfterLayoutCallback callback;
}

class RenderAfterLayout extends RenderProxyBox {
  RenderAfterLayout(this.callback);

  ValueSetter<RenderAfterLayout> callback;
  @override
  void performLayout() {
    super.performLayout();
    //it will call many times
    SchedulerBinding.instance.endOfFrame.then((_) => callback(this));
  }

  Offset get offset => localToGlobal(Offset.zero);
  Rect get rect => Rect.fromLTRB(offset.dx, offset.dy, size.width, size.height);
}
